// 微服务端到端测试报告生成器
export class E2EReportGenerator {
  constructor() {
    this.reportData = {
      timestamp: new Date().toISOString(),
      summary: {
        totalTests: 0,
        passed: 0,
        failed: 0,
        successRate: 0
      },
      services: {},
      scenarios: {},
      performance: {},
      recommendations: []
    }
  }

  // 添加测试结果
  addTestResult(testResult) {
    this.reportData.summary.totalTests++
    
    if (testResult.success) {
      this.reportData.summary.passed++
    } else {
      this.reportData.summary.failed++
    }

    // 按场景分类
    if (testResult.scenario) {
      if (!this.reportData.scenarios[testResult.scenario]) {
        this.reportData.scenarios[testResult.scenario] = {
          total: 0,
          passed: 0,
          failed: 0
        }
      }
      
      this.reportData.scenarios[testResult.scenario].total++
      if (testResult.success) {
        this.reportData.scenarios[testResult.scenario].passed++
      } else {
        this.reportData.scenarios[testResult.scenario].failed++
      }
    }

    // 记录服务健康状态
    if (testResult.serviceHealth) {
      Object.entries(testResult.serviceHealth).forEach(([service, health]) => {
        if (!this.reportData.services[service]) {
          this.reportData.services[service] = {
            healthy: 0,
            unhealthy: 0,
            avgResponseTime: 0,
            totalChecks: 0
          }
        }
        
        this.reportData.services[service].totalChecks++
        if (health.healthy) {
          this.reportData.services[service].healthy++
        } else {
          this.reportData.services[service].unhealthy++
        }
        
        if (health.responseTime) {
          this.reportData.services[service].avgResponseTime = 
            (this.reportData.services[service].avgResponseTime * (this.reportData.services[service].totalChecks - 1) + health.responseTime) / 
            this.reportData.services[service].totalChecks
        }
      })
    }
  }

  // 添加性能测试结果
  addPerformanceResult(performanceResult) {
    if (!this.reportData.performance[performanceResult.testName]) {
      this.reportData.performance[performanceResult.testName] = []
    }
    
    this.reportData.performance[performanceResult.testName].push(performanceResult)
  }

  // 生成建议
  generateRecommendations() {
    // 计算成功率
    this.reportData.summary.successRate = 
      (this.reportData.summary.passed / this.reportData.summary.totalTests) * 100

    // 基于成功率生成建议
    if (this.reportData.summary.successRate < 90) {
      this.reportData.recommendations.push({
        type: 'critical',
        message: '端到端测试成功率较低，建议检查微服务间通信和依赖关系',
        priority: 'high'
      })
    } else if (this.reportData.summary.successRate < 95) {
      this.reportData.recommendations.push({
        type: 'warning',
        message: '端到端测试成功率有待提高，建议优化服务间通信',
        priority: 'medium'
      })
    }

    // 基于服务健康状态生成建议
    Object.entries(this.reportData.services).forEach(([service, stats]) => {
      const healthRate = stats.healthy / stats.totalChecks
      
      if (healthRate < 0.8) {
        this.reportData.recommendations.push({
          type: 'critical',
          message: `${service}服务健康状态不稳定，建议检查服务配置和依赖`,
          priority: 'high',
          service: service,
          healthRate: healthRate
        })
      } else if (healthRate < 0.95) {
        this.reportData.recommendations.push({
          type: 'warning',
          message: `${service}服务偶尔出现健康问题，建议监控服务状态`,
          priority: 'medium',
          service: service,
          healthRate: healthRate
        })
      }
    })

    // 基于性能测试结果生成建议
    Object.entries(this.reportData.performance).forEach(([testName, results]) => {
      const avgResponseTime = results.reduce((sum, r) => sum + (r.avgResponseTime || 0), 0) / results.length
      
      if (avgResponseTime > 5000) {
        this.reportData.recommendations.push({
          type: 'performance',
          message: `${testName}响应时间过长，建议优化性能`,
          priority: 'medium',
          testName: testName,
          avgResponseTime: avgResponseTime
        })
      }
    })
  }

  // 生成HTML报告
  generateHTMLReport() {
    this.generateRecommendations()
    
    const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微服务端到端测试报告</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 2.5em;
        }
        .header .timestamp {
            opacity: 0.8;
            margin-top: 10px;
        }
        .summary {
            padding: 30px;
            border-bottom: 1px solid #eee;
        }
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .summary-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        .summary-card h3 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .summary-card .value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        .success-rate {
            color: ${this.reportData.summary.successRate >= 90 ? '#28a745' : this.reportData.summary.successRate >= 80 ? '#ffc107' : '#dc3545'};
        }
        .content {
            padding: 30px;
        }
        .section {
            margin-bottom: 40px;
        }
        .section h2 {
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        .service-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .service-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        .service-card h4 {
            margin: 0 0 15px 0;
            color: #333;
        }
        .service-stats {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .recommendations {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        .recommendation {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
            border-left: 4px solid;
        }
        .recommendation.critical {
            background: #f8d7da;
            border-left-color: #dc3545;
        }
        .recommendation.warning {
            background: #fff3cd;
            border-left-color: #ffc107;
        }
        .recommendation.performance {
            background: #d1ecf1;
            border-left-color: #17a2b8;
        }
        .priority {
            font-weight: bold;
            text-transform: uppercase;
            font-size: 0.8em;
        }
        .performance-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .performance-table th,
        .performance-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .performance-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>微服务端到端测试报告</h1>
            <div class="timestamp">生成时间: ${new Date(this.reportData.timestamp).toLocaleString('zh-CN')}</div>
        </div>
        
        <div class="summary">
            <h2>测试摘要</h2>
            <div class="summary-grid">
                <div class="summary-card">
                    <h3>总测试数</h3>
                    <div class="value">${this.reportData.summary.totalTests}</div>
                </div>
                <div class="summary-card">
                    <h3>通过测试</h3>
                    <div class="value">${this.reportData.summary.passed}</div>
                </div>
                <div class="summary-card">
                    <h3>失败测试</h3>
                    <div class="value">${this.reportData.summary.failed}</div>
                </div>
                <div class="summary-card">
                    <h3>成功率</h3>
                    <div class="value success-rate">${this.reportData.summary.successRate.toFixed(1)}%</div>
                </div>
            </div>
        </div>
        
        <div class="content">
            <div class="section">
                <h2>服务健康状态</h2>
                <div class="service-grid">
                    ${Object.entries(this.reportData.services).map(([service, stats]) => `
                        <div class="service-card">
                            <h4>${service}</h4>
                            <div class="service-stats">
                                <span>健康检查: ${stats.healthy}/${stats.totalChecks}</span>
                                <span>健康率: ${((stats.healthy / stats.totalChecks) * 100).toFixed(1)}%</span>
                            </div>
                            <div class="service-stats">
                                <span>平均响应时间: ${stats.avgResponseTime.toFixed(0)}ms</span>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div class="section">
                <h2>测试场景结果</h2>
                <div class="service-grid">
                    ${Object.entries(this.reportData.scenarios).map(([scenario, stats]) => `
                        <div class="service-card">
                            <h4>${scenario}</h4>
                            <div class="service-stats">
                                <span>通过: ${stats.passed}/${stats.total}</span>
                                <span>成功率: ${((stats.passed / stats.total) * 100).toFixed(1)}%</span>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            ${Object.keys(this.reportData.performance).length > 0 ? `
            <div class="section">
                <h2>性能测试结果</h2>
                ${Object.entries(this.reportData.performance).map(([testName, results]) => `
                    <h3>${testName}</h3>
                    <table class="performance-table">
                        <thead>
                            <tr>
                                <th>测试项</th>
                                <th>平均响应时间</th>
                                <th>成功率</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${results.map(result => `
                                <tr>
                                    <td>${result.testName || 'N/A'}</td>
                                    <td>${(result.avgResponseTime || 0).toFixed(0)}ms</td>
                                    <td>${result.success ? '通过' : '失败'}</td>
                                    <td>${result.success ? '✅' : '❌'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                `).join('')}
            </div>
            ` : ''}
            
            ${this.reportData.recommendations.length > 0 ? `
            <div class="section">
                <h2>建议和改进</h2>
                <div class="recommendations">
                    ${this.reportData.recommendations.map(rec => `
                        <div class="recommendation ${rec.type}">
                            <div class="priority">${rec.priority} - ${rec.type.toUpperCase()}</div>
                            <div>${rec.message}</div>
                            ${rec.service ? `<div>相关服务: ${rec.service}</div>` : ''}
                            ${rec.healthRate ? `<div>健康率: ${(rec.healthRate * 100).toFixed(1)}%</div>` : ''}
                            ${rec.avgResponseTime ? `<div>平均响应时间: ${rec.avgResponseTime.toFixed(0)}ms</div>` : ''}
                        </div>
                    `).join('')}
                </div>
            </div>
            ` : ''}
        </div>
    </div>
</body>
</html>
    `
    
    return html
  }

  // 生成JSON报告
  generateJSONReport() {
    this.generateRecommendations()
    return JSON.stringify(this.reportData, null, 2)
  }

  // 保存报告到文件
  saveReport(filename = 'e2e-test-report') {
    const html = this.generateHTMLReport()
    const json = this.generateJSONReport()
    
    // 在Cypress环境中，我们可以使用cy.writeFile来保存文件
    cy.writeFile(`cypress/reports/${filename}.html`, html)
    cy.writeFile(`cypress/reports/${filename}.json`, json)
    
    cy.log(`测试报告已保存到 cypress/reports/${filename}.html`)
  }
}

// 导出单例实例
export const e2eReportGenerator = new E2EReportGenerator()

// Cypress命令扩展
Cypress.Commands.add('generateE2EReport', (filename) => {
  e2eReportGenerator.saveReport(filename)
})
